package com.why.blog.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.collections.map.HashedMap;

import java.util.Date;
import java.util.Map;

public class JwtTokenUtils {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "jwtsecretdemo";
    private static final String ISS = "testwu";
    //角色的key
    private static final String ROLE_CLAIMS = "rol";

    //过期时间是一个小时
    private static final long EXPIRATION = 604800L;
    //选择了记住我之后 过期时间半个月
    private static final long EXPIRATION_REMEMBER = 1209600L;

    //创建token
    public static String createToken(String username, String role, boolean isRememberMe,String id) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        Map<String, Object> map = new HashedMap();
        map.put(ROLE_CLAIMS, role);
        map.put("userId",id);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setClaims(map)
                .setIssuer(ISS)
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .compact();
    }


    private static Claims getTokenBody(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            throw  new BusinessRuntimeException(ResponseCode.USER_LIMITATION,"你号没了");
        }

    }

    //获取用户角色
    public static String getUserRole(String token) {
        return (String) getTokenBody(token).get(ROLE_CLAIMS);
    }

    //从token中取出用户名
    public static String getUsername(String token) {
        return getTokenBody(token).getSubject();
    }

    //获取用户id
    public static String getUserId(String token) {
        return (String) getTokenBody(token).get("userId");
    }

    //是否已经过期
    public static boolean isExpiration(String token) {
        return getTokenBody(token).getExpiration().before(new Date());
    }
}
